package com.jiang.jixiang.tools;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.view.View;

import com.jiang.jixiang.R;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.ws.universal.tools.Constants;
import com.ws.universal.tools.utils.ToastUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ShareHelper {
    public static IWXAPI mWechatApi = null;
    private static Context context;

    public static void init(Context ctx) {
        context = ctx;
        mWechatApi = WXAPIFactory.createWXAPI(ctx, Constants.APP_ID);
        mWechatApi.registerApp(Constants.APP_ID);
    }


    /* TODO 微信 share bgin*/
    private static final int THUMB_SIZE = 150;

    //分享网络资源图片
    public static void shareToWChat(final Activity activity, String title, String content, String thumbBmp, String href, boolean isShareToType) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                URL imageurl = null;
                String imgBmp = thumbBmp;
                try {
                    if (imgBmp.indexOf("https:") < 0) {
                        imgBmp = imgBmp.replace("http:", "https:");
                    }
                    imageurl = new URL(imgBmp);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                try {
                    HttpURLConnection conn = (HttpURLConnection) imageurl.openConnection();
                    conn.setDoInput(true);
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    Bitmap bitmap = BitmapFactory.decodeStream(is);
                    is.close();

                    ShareHelper.shareToWChatMethon(activity, title, content, href, bitmap, isShareToType);
                    bitmap.recycle();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();


    }

    //分享本地资源图片
    public static void shareToWChat2(final Activity activity, String title, String content, String href, boolean isShareToType) {
        new Thread(new Runnable() {
            @Override
            public void run() {

                Bitmap bitmap = BitmapFactory.decodeResource(activity.getResources(), R.mipmap.ic_launcher);

                ShareHelper.shareToWChatMethon(activity, title, content, href, bitmap, isShareToType);
                bitmap.recycle();
            }


        }).start();

    }

    //分享方法
    public static void shareToWChatMethon(final Activity activity, String title, String content, String href, Bitmap bmp, boolean isShareToType) {
        // 先判断有没有安装微信
        if (!mWechatApi.isWXAppInstalled()) {
            ToastUtils.showShort("您未安装微信客户端", 300);
            return;
        }
        Resources res = activity.getResources();
        Bitmap thumbBmp = null;
        //        if (!TextUtils.isEmpty(href)) {
        //            try {
        //
        //                thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true);
        //            } catch (Exception e) {
        //                e.printStackTrace();
        //            }
        //        } else {
        //            bmp = BitmapFactory.decodeResource(activity.getResources(), R.mipmap.ic_launcher);
        //            thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true);
        //        }
        try {

            thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (thumbBmp != null) {
            bmp.recycle();
        }

        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = href;

        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = res.getString(R.string.app_name);
        msg.title = title;
        msg.description = content;

        if (thumbBmp != null) {
            msg.thumbData = bmpToByteArray(thumbBmp, true); // 设置缩略图
        }

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = msg;
        req.scene = isShareToType ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;

        mWechatApi.sendReq(req);
        if (thumbBmp != null) {
            thumbBmp.recycle();
        }
    }


    public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bmp.recycle();
        }

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    private static String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }


    public static Bitmap ShareViewScreenshot(View view) {
        //使控件可以进行缓存
        view.setDrawingCacheEnabled(true);
        //获取缓存的 Bitmap
        Bitmap bitmap = view.getDrawingCache();
        //复制获取的 Bitmap
        bitmap = Bitmap.createBitmap(bitmap);
        //关闭视图的缓存
        view.setDrawingCacheEnabled(false);
        return bitmap;
    }

    /**
     * 对View进行截图
     */
    public static void shareToWechatImg(View view, boolean isShareToType) {
        // 先判断有没有安装微信
        if (!mWechatApi.isWXAppInstalled()) {
            ToastUtils.showShort("您未安装微信客户端", 300);
            return;
        }

        //使控件可以进行缓存
        view.setDrawingCacheEnabled(true);
        //获取缓存的 Bitmap
        Bitmap bitmap = view.getDrawingCache();
        //复制获取的 Bitmap
        bitmap = Bitmap.createBitmap(bitmap);
        //关闭视图的缓存
        view.setDrawingCacheEnabled(false);

        WXImageObject imgObj = new WXImageObject(bitmap);
        WXMediaMessage msg = new WXMediaMessage();
        msg.title = "img";
        msg.mediaObject = imgObj;

        //设置缩略图

        Bitmap thumBmp = Bitmap.createScaledBitmap(bitmap, 30, 50, true);
        bitmap.recycle();
        msg.thumbData = bmpToByteArray(thumBmp, true);

        //构造一个Req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("img");
        req.message = msg;

        req.scene = isShareToType ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
        mWechatApi.sendReq(req);


    }

    public static String dirName;
    public static String fileName;

    public static String saveToLocal(View view, Activity activity, boolean isToast) {
        //使控件可以进行缓存
        view.setDrawingCacheEnabled(true);
        //获取缓存的 Bitmap
        Bitmap bitmap = view.getDrawingCache();
        //复制获取的 Bitmap
        bitmap = Bitmap.createBitmap(bitmap);
        //关闭视图的缓存
        view.setDrawingCacheEnabled(false);

        //生成路径
        dirName = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + File.separator + "老魏读书";
        File appDir = new File(dirName);
        if (!appDir.exists()) {
            appDir.mkdirs();
        }
        //文件名为时间
        long timeStamp = System.currentTimeMillis();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        String sd = sdf.format(new Date(timeStamp));
        fileName = sd + ".jpg";

        //获取文件
        File file = new File(appDir, fileName);
        FileOutputStream fos = null;
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            bitmap.recycle();
            //通知系统相册刷新
            activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(file.getPath()))));
            if (isToast) {
                ToastUtils.showShort("保存成功");
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return dirName + "/" + fileName;
    }


    public static void deleteShareQQImg(Activity activity) {
        //获取文件
        File file = new File(dirName, fileName);
        if (file.exists()) {
            file.delete();
        }
        //通知系统相册刷新
        activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(file.getPath()))));
    }
}
